<?php
/**
 * Created by PhpStorm.
 * User: chenxiaogang
 * Date: 2017/10/25
 * Time: 下午12:07
 */

namespace Coupon\Controller;


use Common\Controller\AdminbaseController;
use Coupon\Model\CouponModel;

/**
 * Class CouponManageController
 * @package     Coupon\Controller
 * @name        优惠券管理
 * @end
 */
class CouponManageController extends AdminbaseController
{
    private $model;

    public function _initialize()
    {
        parent::_initialize();//先执行（里面包含一些校验）
        $this->model = new CouponModel();//优惠券种类表模型
    }

    /**
     * @use          [优惠券列表]
     * @author       chenxiaogang
     * @end
     */
    public function index()
    {
        $where = $this->getCondition();//得到查询条件
        $count = $this->model->getCounts( $where );//得到总条数
        $page = $this->page( $count, 20 );//得到分页类对象
        $limit = $page->firstRow . ',' . $page->listRows;//得到分页信息
        $assign['list'] = $this->model->getList( $where, $limit );//得到记录
        $assign['page'] = $page->show( 'Admin' );//渲染的分页片段
        $assign['users'] = D( 'Users' )->where( [ 'user_status' => 1 ] )->getField( 'id,user_login' );//用户列表
        $this->assign( $assign );
        $this->display();
    }

    /**
     * @use          [新增优惠券种类]
     * @author       chenxiaogang
     * @end
     */
    public function add()
    {
        //测试REDIS
        //$redis = \Common\Lib\Redis\Redis::getInstance();
        //$tmp = $redis->hGet( C( 'COUPON_REDIS_KEY' ), 14 );
        //var_dump(json_decode($tmp));die;
        if(IS_GET) {
            $this->assign( 'is_add', 1 );
            $this->display();
        } elseif(IS_POST) {
            $resp = $this->model->add_coupon( I( 'post.options' ) );
            if($resp['status']) {
                $this->success( $resp['msg'], U( 'index' ) );
            } else {
                $this->error( $resp['msg'], U( 'add' ) );
            }
        }
    }

    /**
     * @use          [修改优惠券种类]
     * @author       chenxiaogang
     * @end
     */
    public function upd()
    {
        if(IS_GET) {
            $id = I( 'get.id' );
            $data['data'] = $this->model->find( $id );
            if(empty( $data['data'] )) {
                $this->error( '找不到该优惠券' );
            }
            $data['is_add'] = 0;
            $this->assign( $data );
            $this->display( 'add' );
        } elseif(IS_POST) {
            $resp = $this->model->upd_coupon( I( 'post.options' ) );
            if($resp['status']) {
                $this->success( $resp['msg'], U( 'index' ) );
            } else {
                $this->error( $resp['msg'], U( 'add' ) );
            }
        }
    }

    /**
     * @use          [将优惠券设置成"已结束"，相当于删除了]
     * @author       chenxiaogang
     * @end
     */
    public function del()
    {
        if($id = I( 'get.id' )) {
            //状态弄为"已结束的"
            if($this->model->where( [ 'status' => 2 ] )->delete( $id )) {
                $this->delCouponInRedisByCouponId( $id );//从redis中删除
                $this->success( '删除成功！' );
            } else {
                $this->error( '删除失败！' );
            }
        } else {
            $this->error( '删除失败' );
        }
    }

    /**
     * @use          [得到查询条件]
     * @author       chenxiaogang
     * @end
     * @return array
     */
    private function getCondition()
    {
        $where = [];
        if($name = I( 'request.name' )) {
            $where['c.name'] = [ 'like', '%' . $name . '%' ];
        }
        if($starts = I( 'request.starts' )) {
            $where['c.create_time'] = [ 'EGT', strtotime( $starts . ' 00:00:00' ) ];
        }
        if($ends = I( 'request.ends' )) {
            $where[' c.create_time'] = [ 'ELT', strtotime( $ends . ' 23:59:59' ) ];
        }
        return $where;
    }

    /**
     * @use          [从redis中删除已经结束的优惠券]
     * @author       chenxiaogang
     * @param $id
     */
    private function delCouponInRedisByCouponId($id)
    {
        $redis = \Common\Lib\Redis\Redis::getInstance();
        $redis->del( C( 'COUPON_REDIS_KEY_PREFIX' ) . $id );//删除指定key的优惠券hash
        $redis->sRem( C( 'COUPON_HAS_SET_REDIS_KEY' ), $id );//删除集合中的ID
    }

}